package org.christopher.mybatisplusdemo.controller;

import org.christopher.mybatisplusdemo.common.JsonData;
import org.christopher.mybatisplusdemo.common.UserCondition;
import org.christopher.mybatisplusdemo.entity.User;
import org.christopher.mybatisplusdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

//    @GetMapping("/user")
//    public JsonData queryUser(){
//        List<User> users = userService.selectUserAll();
//        return JsonData.success(users);
//    }

    @GetMapping("/user")
    public JsonData queryUser(@RequestBody UserCondition condition){
        System.out.println(condition);
        List<User> users = userService.selectUserByCondition(condition);
        return JsonData.success(users);
    }

    @PostMapping("/user")
    public JsonData addUsesr(@RequestBody User user){
        int i = userService.addUser(user);
        if(i>0){
            return JsonData.success();
        }else {
            return JsonData.buildError("添加失败");
        }
    }

    @GetMapping("/user/{id}")
    public JsonData queryUser(@PathVariable Integer id){
        User user = userService.selectUserById(id);
        return JsonData.success(user);
    }

    @PutMapping("/user")
    private JsonData updateUser(@RequestBody User user){
        int i = userService.unpdateUser(user);
        if (i>0){
            return JsonData.success();
        }else {
            return JsonData.buildError("修改失败");
        }
    }

    @GetMapping("/users")
    public JsonData queryUsers(){
        List<Integer> ids = new ArrayList<>();
        List<User> users = userService.selectUserByIds(ids);
        return JsonData.success(users);
    }



    @PostMapping("/login")
    public JsonData login(@RequestBody User user){
        System.out.println("用户名密码"+user);
        User loginUser = userService.loginUser(user);
        if(null != loginUser){
            return JsonData.success(loginUser);
        }else{
            return JsonData.buildError("用户名密码错");
        }

    }


}
